<?php
namespace Home\Model;
use Think\Model;
class CartTmpModel extends CommonModel {
	public function  _initialize(){
		parent::_initialize();
		$this->commoditySrv = D('CommodityInfo');
		$this->commoditySrv->ini();
    }
	
	public function getCartList($user_id){
		$result = array();
		$cart_id = C('CART_PRE') . $user_id;//购物袋key
		//获取购物袋信息
		$cart_list_json = $this->getCartTmp($cart_id);
		if(empty($cart_list_json)){
			$result['msg'] = '您的购物袋还是空的';
			$result['isok'] = false;
			return $result;
		}
		
		$result['data']['list'] = json_decode($cart_list_json,true);
		
		$new_cart = array();
		$commodity_sum = 0;
		$sale_sum = 0;
		foreach($result['data']['list'] as $commodity){
			$commodity_info = $this->commoditySrv->commodity_info($commodity['commodity_id']);
			if(empty($commodity_info['is_onsale'])) continue;
			
			$commodity['name'] = $commodity_info['name'];
			$commodity['sale_price'] = $commodity_info['sale_price'];
			$commodity['unit_name'] = get_unit_name($commodity_info['unit_id']);
			$commodity['spec'] = $commodity_info['spec'];
			$commodity['brief_pic'] = $commodity_info['brief_pic'];
			$commodity['brief_sum'] = num_f($commodity['commodity_num']*$commodity['sale_price']);
			$commodity['index'] = $commodity['commodity_id']."_".$commodity['commodity_type'];
			$commodity_sum += num_f($commodity['commodity_num']);
			$sale_sum += num_f($commodity['commodity_num']*$commodity['sale_price']);
			$new_cart[] = $commodity;
		}
		$result['data']['list'] = $new_cart;
		$result['data']['sum']['commodity_sum'] = $commodity_sum;
		$result['data']['sum']['sale_sum'] = $sale_sum;
		$result['isok'] = true;
		return $result;
	}
	
	public function deleteCartAll($user_id){
		$cart_id = C('CART_PRE') . $user_id;//购物袋key
		$this->setCartTmp($cart_id,null);
		return true;
	}

	public function getCartTmp($k,$is_login=true){
		$time1=date("Y-m-d",strtotime("-". C('CART_LIFT_TIME') ." day"))." 03:00:00";
		$time2=date("Y-m-d")." 03:00:00";
		$now = date("Y-m-d H:i:s");
		if($now>$time2){
			$time = $time2;
		}else{
			$time = $time1;
		}
		$dbRes = $this->query("select cart_info from ar_shop.cart_tmp where update_time>'".$time."' and cart_id = '".$k."'");
		if(!empty($dbRes)) return $dbRes[0]['cart_info'];
		else return null;
	}


	public function setCartTmp($k,$v){
		$dbRes = $this->where("cart_id = '".$k."'")->find();
		if(empty($dbRes)){//insert
			$data = array();
			$data['cart_id'] = $k;
			$data['cart_info'] = $v;
			$data['update_time'] = date ( "Y-m-d H:i:s" );
			$this->data($data)->add();
		}else{//update
			$data = array();
			$data['cart_info'] = $v;
			$data['update_time'] = date ( "Y-m-d H:i:s" );
			$this->where("cart_id = '".$k."'")->save($data);
		}
		return true;
	}
}

?>